<?php
include("include/config.inc.php");
if(!isset($_SESSION['s_activId']))
{
  $_SESSION['s_urlRedirectDir'] = $_SERVER['REQUEST_URI'];
  header("Location:checkLogin.php");
}
else
{
	if(isset($_POST['submitBtn']))
	{
		$loopCountC = 0;
		while($loopCountC < count ($_POST['itemIdC']))
		{
			$itemIdC   = ($_POST['itemIdC'][$loopCountC] != '') ? $_POST['itemIdC'][$loopCountC] : 0;
			$quantityC = ($_POST['quantityC'][$loopCountC] != '') ? $_POST['quantityC'][$loopCountC] : 0;
			$rateC     = ($_POST['rateC'][$loopCountC] != '') ? $_POST['rateC'][$loopCountC] : 0;
			$amountC   = ($_POST['amountC'][$loopCountC] != '') ? $_POST['amountC'][$loopCountC] : 0;
			$plusMinusC = '-';
			if($_POST['amountC'][$loopCountC] != '' && $_POST['amountC'][$loopCountC] > 0)
			{
				$insertCDetail = "INSERT INTO consumtion (itemId,quantity,rate,amount)
			                                    VALUES (".$itemIdC.",".$quantityC.",".$rateC.",".$amountC.")";
			  $insertCDetailRes = mysql_query($insertCDetail);
			  insertItemStock($itemIdC,$quantityC,$plusMinusC);
			}
			$loopCountC++;
		}
		$loopCountP = 0;
		while($loopCountP < count ($_POST['itemIdP']))
		{
			$itemIdP   = ($_POST['itemIdP'][$loopCountP] != '') ? $_POST['itemIdP'][$loopCountP] : 0;
			$quantityP = ($_POST['quantityP'][$loopCountP] != '') ? $_POST['quantityP'][$loopCountP] : 0;
			$rateP     = ($_POST['rateP'][$loopCountP] != '') ? $_POST['rateP'][$loopCountP] : 0;
			$amountP   = ($_POST['amountP'][$loopCountP] != '') ? $_POST['amountP'][$loopCountP] : 0;
			$plusMinusP = '+';
			if($_POST['amountP'][$loopCountP] != '' && $_POST['amountP'][$loopCountP] > 0)
			{
				$insertPDetail = "INSERT INTO production (itemId,quantity,rate,amount)
			                                    VALUES (".$itemIdP.",".$quantityP.",".$rateP.",".$amountP.")";
			  $insertPDetailRes = mysql_query($insertPDetail);
			  insertItemStock($itemIdP,$quantityP,$plusMinusP);
			}
			$loopCountP++;
		}
		header("Location:consumtionProduction.php");
	}
	
	$itemArray = array();
	$i = 0;
	$selectItem = "SELECT itemId,itemName,itemUnit
	                 FROM item
	                ORDER BY itemName";
	$selectItemRes = mysql_query($selectItem);
	while($itemRow = mysql_fetch_array($selectItemRes))
	{
		$itemArray['itemId'][$i]   = $itemRow['itemId'];
		$itemArray['itemName'][$i] = $itemRow['itemName'];
		$i++;
	}
}
include("bottom.php");
$smarty->assign('itemArray',$itemArray);
$smarty->display('consumtionProduction.tpl');
?>